import GpContainer from "@/components/GpContainer";
import { useNavigateEventChannel } from "@/hooks/useNavigateEventChannel";
import { debounce } from "@/utils/helper";
import { navigate } from "@/utils/navigation";
import { SafeArea } from "@taroify/core";
import { Button, Input, InputProps, ScrollView, Text, View } from "@tarojs/components";
import Taro from "@tarojs/taro";
import React, { useEffect, useRef, useState } from "react";
import { useImmer } from "use-immer";

type SearchItem = {
  node: React.ReactNode[]
  item: Awaited<ReturnType<FieldEditStateSearch["searchAction"]>>[number]
}
export default function Index() {
  const searchActionRef = useRef<FieldEditStateSearch["searchAction"]>()
  const [state, setState] = useImmer<Omit<FieldEditStateSearch, "searchAction">>({
    navigationbarTitleText: "",
    maxContent: 40,
    placeholder: ""
  })
  const { eventChannel } = useNavigateEventChannel()
  const [searchList, setSearchList] = useState<SearchItem[]>([])
  const triggerSearch = debounce(300, async (value: string) => {
    const text = value.trim()
    if (text.length === 0) {
      setSearchList([])
      return;
    }
    const regEx = new RegExp(`(${text})`, "i");
    const available = await searchActionRef.current!(text)
    const nodes = available
    .filter(item => regEx.test(item.label))
    .map(item => {
      const spliter = React.createElement(Text, {
        className: "text-theme"
      }, text)
      const parts = item.label.split(regEx).map<React.ReactNode>(part => {
        if (part === text) return spliter
        return part
      })
      return {
        node: parts,
        item
      }
    })
    setSearchList(nodes)
  })
  useEffect(() => {
    if (eventChannel) {
      eventChannel.once("getField", (value: FieldEditStateSearch) => {
        if (value) {
          const { searchAction, ...s } = value
          setState({...state, ...s})
          searchActionRef.current = searchAction
          Taro.setNavigationBarTitle({
            title: value.navigationbarTitleText
          })
        }
      })
    }
  }, [])
  const handleSubmit = () => {
    const content = state.content?.trim()
    if (!content) {
      Taro.showToast({
        title: state.placeholder,
        icon: "none"
      })
      return
    }
    eventChannel && eventChannel.emit("receiveField", { label: content, value: state.contentId })
    navigate()
  }
  const syncLength: InputProps['onInput'] = ({ detail }) => {
    setState(draft => {
      draft.content = detail.value
      draft.contentId = void 0
    })
    triggerSearch(detail.value)
  }
  return (
    <GpContainer className="bg-white">
      <View className="box-border px-[32px] flex flex-col mt-[8px]">
        <View className="border-b border-solid border-b-[#EEEEEE] py-[40px]">
          <Input name="name" placeholder={state.placeholder} maxlength={state.maxContent} className="border-0 outline-0 text-primary text-[32px]" value={state.content} onInput={syncLength} />
        </View>
        {
          state.content?.length
          ? (
            <ScrollView
              scrollY
              scrollWithAnimation
              style={{height: "60vh"}}
            >
              {
                searchList.map(l => (
                  <View key={l.item.value} onClick={() => setState(draft => {draft.content = l.item.label; draft.contentId = l.item.value;})} className="text-[32px] text-third border-b-2 border-solid border-b-[#EEEEEE] h-[130px] flex flex-row items-center">
                    {l.node}
                  </View>
                ))
              }
            </ScrollView>
          ) : (
            <View className="flex flex-row items-center justify-end text-[24px] mt-[24px]">
              <Text className="text-theme">{state.content?.length || 0}</Text>
              <Text className="text-third">/{state.maxContent}</Text>
            </View>
          )
        }
      </View>
      <View className="fixed bottom-0 left-0 right-0 px-[32px] pb-[32px] pt-[16px]">
        <Button className="text-center bg-theme h-[80px] leading-[80px] box-border rounded-[64px]" onClick={handleSubmit}>
          <Text className="text-white text-[32px]">保存</Text>
        </Button>
        <SafeArea position="bottom"/>
      </View>
    </GpContainer>
  )
}
